define(["jquery", "easy-admin"], function ($, ea) {

    var init = {
        index_url: '/manage/member/miniapp/index',
        app_url: '/manage/member/miniapp/my/index',
        detail_url: 'member/miniapp/detail',
    };
    var laytpl = layui.laytpl;
    var element=layui.element;
    var Controller = {
        index: function () {
            app.init();
            ea.listen();
        },
        detail: function () {
            //应用详情
            element.init();
            app.buy_listen();
            app.plugin_listen();
            app.img_listen();
        }
    };


    //操作对象
    var app = {
        data: {
            app_id: app_id,
            buy:true,
            detail_info:{},
            miniapp_module: {},
            price_info: {},
        },
        init: function () {
            //加载应用店铺数据
            this.setAppShopList();
            this.setAppBuyList();
            this.detail_listen();
            this.in_app_listen();
        },
        setAppShopList: function () {
            var _this = this;
            ea.request.post({
                url: init.index_url,
            }, function (res) {
                _this.loadList(res.data.data, laytpl);//插件列表渲染
            }, function (res) {
                ea.msg.error(res.msg); //失败
            }, function (that) {
                ea.msg.error('查询失败');//异常
            });
        },
        setAppBuyList:function(){
            ea.request.get(
                {
                    url: init.app_url,
                    data: {},
                }, function (res) {
                    var list = res.data.data.list;
                    //渲染插件
                    var getTpl = app_buy_template.innerHTML
                        , table = document.getElementsByClassName('table')[0];
                    laytpl(getTpl).render(list, function (html) {
                        table.innerHTML += html;
                    });
                }
            );

        },
        loadList: function (data, laytpl) {
            //渲染插件
            var getTpl = app_shop_template.innerHTML
                , view = document.getElementById('shop_app_list');
            laytpl(getTpl).render(data.list, function (html) {
                view.innerHTML = html;
            });
        },
        detail_listen:function () { //插件详情
            var _this = this;
            $('body').on('click', '.app-item', function (event) {
                _this.data.app_id = $(this).attr('data-id');
                _this.jump_detail();
                return false;
            });
        }
        ,jump_detail:function () {
            window.location.href = '/manage/member/miniapp/detail?id='+this.data.app_id;
        },
        in_app_listen:function () {
            var _this = this;
            //监听列表内管理应用按钮被点击
            $('body').off('click', '[data-event]').on('click', '[data-event]', function (event) {
                var miniapp_dir = $(this).attr('data-dir');
                var events = $(this).attr('data-event');
                switch(events) {
                    case 'open':
                        //将目标应用的目录写入cookie,在租户首页进行消费
                        ea.common.setCookie('miniapp_dir', miniapp_dir, 's60');
                        parent.window.location = '/manage/member/index';
                        break;
                    case 'renew':
                        _this.data.app_id = $(this).attr('data-id');
                        _this.jump_detail();
                        break;

                }
                event.stopPropagation();

            })
        },
        buy_listen:function () {
            //初始化套餐数据和价格参数
            this.initBuyData();
            this.module_listen();
            this.price_listen();
            var _this = this;
            $('body').on('click', '.app-buy', function (event) {
                var id = $(this).attr('data-id');
                var type = $(this).attr('data-type');
                var price_id = $(this).attr('data-price-id');

                //如果未购买过应用则输入自定义应用名
                if(!_this.data.detail_info.hasBuy){
                    var content = "<span style=\"color: red\">( 注意:如果您已购买过其他套餐，购买该套餐后其他套餐将失效，请知悉！ )</span>" +
                        "<input id='name' type=\"text\" placeholder=\"请输入自定义应用名称\" class=\"layui-input\">" +
                        "<input id='paypwd' type=\"password\" placeholder=\"请输入6位数字支付密码\" class=\"layui-input\">";
                }else{
                    var content = "<span style=\"color: red\">( 注意:如果您已购买过其他套餐，购买该套餐后其他套餐将失效，请知悉！ )</span>" +
                        "<input id='paypwd' type=\"password\" placeholder=\"请输入6位数字支付密码\" class=\"layui-input\">";
                }
                layer.open({
                    title: '确认【购买/续费】',
                    type: 1,
                    area: ['300px', '220px'],
                    closeBtn: 0,
                    content: content
                    ,shadeClose: true
                    ,btn: ['支付']
                    , btnAlign: 'c' //按钮居中
                    ,yes: function(index, layero){
                        var paypwd = $('#paypwd').val();
                        var  pattern = /\d{6}/;
                        if(!paypwd || !pattern.test(paypwd)) {
                            layer.msg('请输入6位数字密码', {icon: 2, time:1000});
                            return;
                        }

                        var name = $('#name').val();
                        if(!_this.data.detail_info.hasBuy && !paypwd) {
                            layer.msg('请填写应用名称', {icon: 2, time:1000});
                            return;
                        }

                        var data = {
                            id: id,
                            paypwd: paypwd,
                            name: name,
                            price_id: price_id,
                        };

                        ea.request.post(
                            {
                                url: '/manage/member/miniapp/buy',
                                data: data,
                            }, function (res) {
                                layer.msg('购买成功', {icon: 1}, function () {
                                    location.reload();//功能购买成功后刷新应用详情页面
                                });
                            }
                        );


                        // ea.request.post("{:Url('/manage/member/miniapp/buy')}", data)
                        //     .then(function (response) {
                        //         if (response.data.data.errcode === 0) {
                        //             layer.msg('购买成功', {icon: 1}, function () {
                        //                 location.reload();//功能购买成功后刷新应用详情页面
                        //             });
                        //         } else layer.msg(response.data.msg, {icon: 2});
                        //     })
                        layer.close(index);
                    }
                });

            });

            //监听充值
            $('body').on('click', '.go-recharge', function (event) {
                ea.open('租户金额充值', '/manage/member/recharge', '100%', '100%');
            });


        },
        plugin_listen:function () {
            $('body').on('click', '.plugin-buy', function (event) {
                var id = $(this).attr('data-id');
                var app = $(this).attr('data-app-id');

                //重定向到插件详情
                window.location.href = '/manage/member/plugin/detail?source='+app+'&id='+id;

            });
        },
        img_listen:function () {
            var imgList = $('.img')
            console.log($(window).height())
            $('.rgba-bag').css({
                "width": $(window).width(),
                "height": $(window).height(),
                "background": "rgba(0, 0, 0, 0.5)"
            })
            let show = false
            for (let i = 0; i < imgList.length; i++) {
                imgList[i].onclick = function() {
                    if (show == false) {
                        $(".rgba-bag-img")[0].innerHTML = `
                        <img src="${$(".img img ")[i].src}">
                        `
                        $(".rgba-bag ").css({
                            "display": "block"
                        })
                        show = true
                    }
                }
            }
            $(".rgba-bag ").click(function(){
                $(this).css({
                    "width": "100%",
                    "height": "100%"
                })
                $(".rgba-bag ").css({
                    "display": "none"
                })
                show = false
            })
        },
        module_listen:function () {
            var _this = this;
            //监听套餐选择
            $('body').on('click', '.module-item', function (event) {
                //增加选中样式
                $(".module-item").removeClass("checkModule");
                $(this).addClass("checkModule");
                //触发价格规格改变
                var module_index = $(this).attr('data-index');
                _this.data.miniapp_module = _this.data.detail_info.baseModules[module_index];
                _this.setPrice();
            });
        },
        price_listen:function () {
            var _this = this;
            //监听规格价格
            $('body').on('click', '.price-it', function (event) {
                //增加选中样式
                $(".price-it").removeClass("checkModule");
                $(this).addClass("checkModule");
                //触发价格结算
                var price_index = $(this).attr('data-index');
                _this.data.price_info = _this.data.miniapp_module.price_list[price_index];
                console.log( _this.data.price_info.title);
                _this.settlePrice();//渲染结算数据
            });
        },
        initBuyData: function () {
            var _this = this;
            ea.request.post({
                url: '/' + CONFIG.ADMIN + '/' + init.detail_url + '?id='+ app.data.app_id,
            }, function (res) {
                //得到详情数据
                _this.data.detail_info = res.data.data;
                //渲染详情
                _this.setDetail();
                //默认选中第一个
                _this.data.detail_info.baseModules[0].check_style = 'checkModule';
                _this.setModule();//插件列表渲染
                //渲染默认价格规格
               _this.data.miniapp_module = _this.data.detail_info.baseModules[0];
                _this.setPrice();//价格规格渲染

            }, function (res) {
                ea.msg.error(res.msg); //失败
            }, function (that) {
                ea.msg.error('查询失败');//异常
            });
        },
        setModule:function () {
            //生成价格套餐
            var getTpl = module_template.innerHTML;
            laytpl(getTpl).render(this.data.detail_info.baseModules, function (html) {
                $("#module_list").html(html);
            });
        },
        setPrice:function () {
            console.log(this.data.miniapp_module.price_list);
            //生成价格套餐
            var getTpl = price_template.innerHTML;
            laytpl(getTpl).render(this.data.miniapp_module.price_list, function (html) {
                $("#price_list").html(html);
            });
            //隐藏结算数据
            $('.settle-total').hide();
        },
        settlePrice:function () {
            //组装计算结果
            var price_info = this.data.price_info;
            //得到套餐名
            price_info.module_title = this.data.miniapp_module.name;
            //得到是否已购买
            price_info.has_buy = this.data.miniapp_module.has_buy;
            //模块id
            price_info.module_id = this.data.miniapp_module.id;
            //模块type
            price_info.module_type = this.data.miniapp_module.type;
            //当前余额
            price_info.my_price = this.data.detail_info.price;
            var getTpl = total_template.innerHTML;
            laytpl(getTpl).render(price_info, function (html) {
                $('.settle-total').show();
                $("#price-content").html(html);
            });
        },
        setDetail:function () {
            //渲染购买情况
            var getTpl = detail_template.innerHTML;
            laytpl(getTpl).render(this.data.detail_info.miniappOrder, function (html) {
                $("#app_detail").html(html);
            });
        }

    };


    return Controller;
});